const net = require('net')
const chatServer = net.createServer()
const clientList = []
const chalk = require('chalk')

let clientNum = 0

chatServer.on('connection', client=>{
    clientList.push(client)

    client.name = `guest${++clientNum}:${client.remotePort}`
    const welcomeMessage = `欢迎 ${chalk.green(client.name)} 来到 呱呱聊天室。\n`

    broadcast(welcomeMessage, client)

    client.on('data',data=>{
        broadcast(data, client)
    })

    client.on('end', () => {
        clientList.splice(clientList.indexOf(client), 1)
        // broadcast(`${client.name}退出了直播间`,client)
    })

    client.on('error', err => {
        console.log(err)
    })
})

function broadcast(message, client) {
    const cleanup = []
    let i = clientList.length
    while(i--) {
        if (client !== clientList[i]) {
            if (clientList[i].writable) {
                clientList[i].write(client.name+':'+message)
            } else {
                cleanup.push(clientList[i])
                clientList[i].destroy()
            }
        }
    }
    for(i=0;i<cleanup.length;i+=1) {
        clientList.splice(clientList.indexOf(cleanup[i]), 1)
    }
}


chatServer.listen(9000)
// 以上只能通过命令行访问
// $  telnet localhost 9000
